import React, { useState } from 'react';
import { RoomStatus } from '../../../types/room';
import { RoomStatusManager, StatusCategory } from '../utils/RoomStatusManager';
import EnhancedStatusIndicator from './EnhancedStatusIndicator';
import styles from '../styles/StatusLegend.module.css';

interface StatusLegendProps {
  onStatusFilter?: (statuses: RoomStatus[]) => void;
  selectedStatuses?: RoomStatus[];
  compact?: boolean;
}

const StatusLegend: React.FC<StatusLegendProps> = ({
  onStatusFilter,
  selectedStatuses = [],
  compact = false,
}) => {
  const [isExpanded, setIsExpanded] = useState(!compact);
  const [activeCategory, setActiveCategory] = useState<StatusCategory | 'all'>(
    'all'
  );

  // 按分类组织状态
  const statusesByCategory = {
    [StatusCategory.BOOKING]: RoomStatusManager.getStatusesByCategory(
      StatusCategory.BOOKING
    ),
    [StatusCategory.CLEANING]: RoomStatusManager.getStatusesByCategory(
      StatusCategory.CLEANING
    ),
    [StatusCategory.MAINTENANCE]: RoomStatusManager.getStatusesByCategory(
      StatusCategory.MAINTENANCE
    ),
    [StatusCategory.SPECIAL]: RoomStatusManager.getStatusesByCategory(
      StatusCategory.SPECIAL
    ),
  };

  const categoryLabels = {
    [StatusCategory.BOOKING]: '🏨 预订管理',
    [StatusCategory.CLEANING]: '🧹 清洁流程',
    [StatusCategory.MAINTENANCE]: '🔧 维护维修',
    [StatusCategory.SPECIAL]: '⚠️ 特殊状态',
  };

  const handleStatusToggle = (status: RoomStatus) => {
    if (!onStatusFilter) return;

    const newSelectedStatuses = selectedStatuses.includes(status)
      ? selectedStatuses.filter(s => s !== status)
      : [...selectedStatuses, status];

    onStatusFilter(newSelectedStatuses);
  };

  const handleCategoryToggle = (category: StatusCategory | 'all') => {
    if (!onStatusFilter) return;

    if (category === 'all') {
      onStatusFilter([]);
      setActiveCategory('all');
    } else {
      const categoryStatuses = statusesByCategory[category];
      const allCategorySelected = categoryStatuses.every(status =>
        selectedStatuses.includes(status)
      );

      if (allCategorySelected) {
        // 取消选择该分类的所有状态
        onStatusFilter(
          selectedStatuses.filter(status => !categoryStatuses.includes(status))
        );
      } else {
        // 选择该分类的所有状态
        const newSelected = [...selectedStatuses];
        categoryStatuses.forEach(status => {
          if (!newSelected.includes(status)) {
            newSelected.push(status);
          }
        });
        onStatusFilter(newSelected);
      }
      setActiveCategory(category);
    }
  };

  const getStatusCount = (status: RoomStatus): number => {
    // 这里可以传入实际的统计数据
    // 现在返回模拟数据
    const mockCounts: Record<RoomStatus, number> = {
      [RoomStatus.AVAILABLE]: 45,
      [RoomStatus.BOOKED]: 23,
      [RoomStatus.OCCUPIED]: 18,
      [RoomStatus.CHECKED_OUT]: 8,
      [RoomStatus.CLEANING]: 5,
      [RoomStatus.DIRTY]: 3,
      [RoomStatus.MAINTENANCE]: 2,
      [RoomStatus.VIP_BOOKED]: 4,
      [RoomStatus.PARTIALLY_BOOKED]: 1,
      [RoomStatus.CLEANED]: 7,
      [RoomStatus.DEEP_CLEANING]: 1,
      [RoomStatus.INSPECTING]: 2,
      [RoomStatus.ROUTINE_MAINTENANCE]: 0,
      [RoomStatus.DEEP_MAINTENANCE]: 0,
      [RoomStatus.REPAIR]: 1,
      [RoomStatus.EQUIPMENT_REPLACEMENT]: 0,
      [RoomStatus.LOCKED]: 0,
      [RoomStatus.TEMPORARILY_UNAVAILABLE]: 1,
      [RoomStatus.OUT_OF_ORDER]: 0,
    };
    return mockCounts[status] || 0;
  };

  if (compact && !isExpanded) {
    return (
      <div className={styles.compactLegend}>
        <button
          className={styles.expandButton}
          onClick={() => setIsExpanded(true)}
          title='展开状态图例'
        >
          📊 状态图例 ({Object.values(RoomStatus).length})
        </button>
      </div>
    );
  }

  return (
    <div className={styles.statusLegend}>
      <div className={styles.legendHeader}>
        <h3 className={styles.legendTitle}>📊 房间状态图例</h3>
        <div className={styles.legendActions}>
          {compact && (
            <button
              className={styles.collapseButton}
              onClick={() => setIsExpanded(false)}
              title='收起图例'
            >
              ➖
            </button>
          )}
          <button
            className={styles.clearButton}
            onClick={() => handleCategoryToggle('all')}
            title='清除所有筛选'
          >
            🔄 清除筛选
          </button>
        </div>
      </div>

      {/* 分类标签页 */}
      <div className={styles.categoryTabs}>
        <button
          className={`${styles.categoryTab} ${activeCategory === 'all' ? styles.active : ''}`}
          onClick={() => handleCategoryToggle('all')}
        >
          📋 全部
        </button>
        {Object.entries(categoryLabels).map(([category, label]) => {
          const categoryStatuses =
            statusesByCategory[category as StatusCategory];
          const selectedCount = categoryStatuses.filter(status =>
            selectedStatuses.includes(status)
          ).length;

          return (
            <button
              key={category}
              className={`${styles.categoryTab} ${activeCategory === category ? styles.active : ''}`}
              onClick={() => handleCategoryToggle(category as StatusCategory)}
              title={`${label} (${selectedCount}/${categoryStatuses.length} 已选)`}
            >
              {label}
              {selectedCount > 0 && (
                <span className={styles.selectionBadge}>{selectedCount}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* 状态列表 */}
      <div className={styles.statusContainer}>
        {Object.entries(statusesByCategory).map(([category, statuses]) => {
          if (activeCategory !== 'all' && activeCategory !== category)
            return null;

          return (
            <div key={category} className={styles.categorySection}>
              {activeCategory === 'all' && (
                <h4 className={styles.categoryHeader}>
                  {categoryLabels[category as StatusCategory]}
                </h4>
              )}

              <div className={styles.statusGrid}>
                {statuses.map(status => {
                  const isSelected = selectedStatuses.includes(status);
                  const count = getStatusCount(status);

                  return (
                    <div
                      key={status}
                      className={`${styles.statusItem} ${isSelected ? styles.selected : ''}`}
                      onClick={() => handleStatusToggle(status)}
                      title={`点击切换筛选 - ${RoomStatusManager.getStatusDescription(status)}`}
                    >
                      <EnhancedStatusIndicator
                        status={status}
                        size='small'
                        showLabel={true}
                        showIcon={true}
                        className={styles.statusIndicator}
                      />
                      <span className={styles.statusCount}>{count}</span>
                      {isSelected && (
                        <div className={styles.selectedMark}>✓</div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>

      {/* 筛选统计 */}
      {selectedStatuses.length > 0 && (
        <div className={styles.filterSummary}>
          <span className={styles.filterText}>
            已筛选 {selectedStatuses.length} 种状态
          </span>
          <button
            className={styles.clearFiltersButton}
            onClick={() => handleCategoryToggle('all')}
          >
            清除筛选
          </button>
        </div>
      )}
    </div>
  );
};

export default StatusLegend;
